from tasks.models import DemoTask

import aiohttp, time


async def handle_demo(task: list):
    if task['job_name'] != DemoTask.job_name:
        return
    demo_obj: DemoTask = await DemoTask.query_one(job_hash=task['job_id'])
    if demo_obj:
        if demo_obj.expire_at < int(time.time()):
            await demo_obj.expire_done()
        else:
            await demo_obj.running()
            async with aiohttp.ClientSession() as session:
                try:
                    resp = await session.get(demo_obj.url, ssl=False)
                    demo_obj.content = await resp.text()
                    await demo_obj.finished_done()
                except Exception as e:
                    demo_obj.message = str(e)
                    await demo_obj.error_done()
